package neu.edu.cn.nuemall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import neu.edu.cn.nuemall.entity.Userinfo;
import neu.edu.cn.nuemall.mapper.UserinfoMapper;
import neu.edu.cn.nuemall.service.UserinfoService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

//实现接口
@Service
public class UserInfoServiceImpl implements UserinfoService {

    @Autowired
    private UserinfoMapper userInfoMapper;
    @Autowired
    private HttpSession session;

    @Override
    public int addUser(Userinfo userInfo){
        userInfo.setPassword(DigestUtils.sha256Hex(DigestUtils.sha256Hex(userInfo.getPassword())));
        int i=userInfoMapper.insert(userInfo);
        return i;
    }

    @Override
    public List<Userinfo> getUserList(Userinfo userinfo) {
        QueryWrapper<Userinfo> queryWrapper=new QueryWrapper<Userinfo>();
        queryWrapper.eq("name",userinfo.getName());
        queryWrapper.eq("password",userinfo.getPassword());

        List<Userinfo> userinfoList=userInfoMapper.selectList(queryWrapper);
        return userinfoList;
    }

    @Override
    public String getCurrentUser() {
        Userinfo userinfo=(Userinfo) session.getAttribute("USER_INFO");
        String userId=userinfo.getId();
        return userId;
    }

    @Override
    public Userinfo getUserByName(String number) {
        QueryWrapper<Userinfo> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("name",number);
        return userInfoMapper.selectOne(userQueryWrapper);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Userinfo> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("name",username);
        List<Userinfo> userList=userInfoMapper.selectList(userQueryWrapper);
        if (userList==null||userList.size()==0){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        Userinfo user=userList.get(0);
        //只要登录了就是基础用户
        List<GrantedAuthority> authorities=new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_BASE_USER"));
        return org.springframework.security.core.userdetails.User
                .withUsername(user.getName())
                .password(user.getPassword())
                .authorities(authorities)
                .build();
    }
}
